package de.sky.mathparser.parser.token;

import java.text.ParseException;

public class Token {
	private TokenType type;
	private double numberContent;
	private char operatorContent;

	public Token(String tokenString) throws ParseException {
		if (tryParseNumber(tokenString)) {
		} else if (tryParseParenthesis(tokenString)) {
		} else if (tryParseOperator(tokenString)) {
		} else {
			throw new ParseException("TokenString could not be parsed: \""
					+ tokenString + "\"", tokenString.length());
		}

	}

	private boolean tryParseOperator(String tokenString) {
		switch (tokenString) {
		case "+":
		case "-":
		case "*":
		case "/":
		case "%":
			this.operatorContent = tokenString.charAt(0);
			this.type = TokenType.OPERATOR;
			return true;
		}
		return false;
	}

	private boolean tryParseParenthesis(String tokenString) {
		if (tokenString.equals("(")) {
			this.type = TokenType.LEFT_PARENTHESIS;
			return true;
		} else if (tokenString.equals(")")) {
			this.type = TokenType.RIGHT_PARENTHESIS;
			return true;
		}
		return false;
	}

	private boolean tryParseNumber(String tokenString) {
		try {
			double d = Double.parseDouble(tokenString);
			this.type = TokenType.NUMBER;
			this.numberContent = d;
		} catch (NumberFormatException e) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		boolean detailed = false;
		switch (type) {
		case NUMBER:
			if (detailed)
				return "Number: " + numberContent;
			return "" + numberContent;
		case OPERATOR:
			if (detailed)
				return "Operator: " + operatorContent;
			return "" + operatorContent;
		case LEFT_PARENTHESIS:
			if (detailed)
				return "Left Parenthesis";
			return "(";
		case RIGHT_PARENTHESIS:
			if (detailed)
				return "Right Parenthesis";
			return ")";
		}

		assert (false);
		return "FAILURE";
	}

	public boolean isToken(TokenType requiredType) {
		return type == requiredType;
	}

	public double getNumber() throws ParseException {
		if (type != TokenType.NUMBER) {
			throw new ParseException("Wrong Token Type: " + type.toString(), 0);
		}
		return numberContent;
	}
	

	public char getOperator() throws ParseException {
		if (type != TokenType.OPERATOR) {
			throw new ParseException("Wrong Token Type: " + type.toString(), 0);
		}
		return operatorContent;
	}
}
